/*
 * The contents of this web application are subject to the Mozilla Public License Version 
 * 1.1 (the "License"); you may not use this web application except in compliance with 
 * the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, 
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
 * for the specific language governing rights and limitations under the License.
 * 
 * The Original Code is owned by and the Initial Developer of the Original Code is 
 * Composite A/S (Danish business reg.no. 21744409). All Rights Reserved
 * 
 * Section 11 of the License is EXPRESSLY amended to include a provision stating 
 * that any dispute, including but not limited to disputes related to the enforcement 
 * of the License, to which Composite A/S as owner of the Original Code, as Initial 
 * Developer or in any other role, becomes a part to shall be governed by Danish law 
 * and be initiated before the Copenhagen City Court ("K�benhavns Byret")            
 */

using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Xml.Linq;
using Composite.Community.TellAFriend.Localization;
using Composite.Community.TellAFriend.Validators;
using Composite.Core.WebClient.Captcha;
using Composite.Core.Xml;

namespace Composite.Community.TellAFriend
{
    public class TellAFriendFacade
    {
        public static IEnumerable<XElement> Send(string fromName, string fromEmail, string toName, string toEmail, string description, string captcha, string captchaEncryptedValue, bool useCaptcha, string website, string url)
        {
            bool isSmtpConfigured = IsSmtpConfigured();
            var catpchaIsValid = !useCaptcha || Captcha.IsValid(captcha, captchaEncryptedValue);

            yield return new XElement("SubmittedData",
                new XAttribute("Fieldname", "fromName"),
                new XAttribute("Value", fromName));
            yield return new XElement("SubmittedData",
                            new XAttribute("Fieldname", "fromEmail"),
                            new XAttribute("Value", fromEmail));
            yield return new XElement("SubmittedData",
                            new XAttribute("Fieldname", "toName"),
                            new XAttribute("Value", toName));
            yield return new XElement("SubmittedData",
                            new XAttribute("Fieldname", "toEmail"),
                            new XAttribute("Value", toEmail));
            yield return new XElement("SubmittedData",
                            new XAttribute("Fieldname", "description"),
                            new XAttribute("Value", description));
            yield return new XElement("SubmittedData",
                            new XAttribute("Fieldname", "captcha"),
                            new XAttribute("Value", catpchaIsValid));

            // Input error ?
            if (!isSmtpConfigured || string.IsNullOrEmpty(fromName) || !RegExp.Validate(RegExpLib.Email, fromEmail, true) || string.IsNullOrEmpty(toName) || !RegExp.Validate(RegExpLib.Email, toEmail, true) || !catpchaIsValid)
            {
                var errorText = new Hashtable();

                if (!isSmtpConfigured)
                {
                    errorText.Add("missingSMTP", Resource.GetLocalized("TellAFriend", "missingSMTP"));
                }

                if (string.IsNullOrEmpty(fromName))
                {
                    errorText.Add("fromName", Resource.GetLocalized("TellAFriend", "fromNameError"));
                }

                if (!RegExp.Validate(RegExpLib.Email, fromEmail, true))
                {
                    errorText.Add("fromEmail", Resource.GetLocalized("TellAFriend", "fromEmailError"));
                }

                if (string.IsNullOrEmpty(toName))
                {
                    errorText.Add("toName", Resource.GetLocalized("TellAFriend", "toNameError"));
                }

                if (!RegExp.Validate(RegExpLib.Email, toEmail, true))
                {
                    errorText.Add("toEmail", Resource.GetLocalized("TellAFriend", "toEmailError"));
                }

                if (!catpchaIsValid)
                {
                    errorText.Add("captcha", Resource.GetLocalized("TellAFriend", "captchaError"));
                }

                foreach (string key in errorText.Keys)
                {
                    yield return new XElement("Error",
                                 new XAttribute("Fieldname", key),
                                 new XAttribute("ErrorDescription", errorText[key].ToString()));
                }
            }
            else
            {
                var from = new MailAddress(fromEmail, fromName);
                var to = new MailAddress(toEmail, toName);
                url = url.Replace("&TellAFriend=1", "").Replace("?TellAFriend=1", "");
                var subject = string.Format("{0} {1}", Resource.GetLocalized("TellAFriend", "emailSubject"), website);
                //var body = string.Format("{0}<br />{1}: {2}", description, Resource.GetLocalized("TellAFriend", "emailBody"),  url);
                var emailBody = Resource.GetLocalized("TellAFriend", "emailBody");
                var body = string.Format(emailBody, description.Replace("\n", "<br />"), url);

                Email.Send(from, to, from, null, subject, body, true, MailPriority.Normal);
            }
        }

        public static XsltExtensionDefinition<TellAFriendXsltExtensionsFunction> XsltExtensions()
        {
            return new XsltExtensionDefinition<TellAFriendXsltExtensionsFunction>
            {
                EntensionObject = new TellAFriendXsltExtensionsFunction(),
                ExtensionNamespace = "#TellAFriendXsltExtensionsFunction"
            };
        }

        public static string GetUrl()
        {
            var url = HttpContext.Current.Request.Url.ToString();
            return string.Format("{0}{1}TellAFriend=1", url, url.Contains("?") ? "&" : "?");
        }

        public static string GetWebsite()
        {
            return HttpContext.Current.Request.Url.DnsSafeHost;
        }

        public static bool IsSmtpConfigured()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
            return (settings.Smtp.DeliveryMethod.ToString() == "Network" && settings.Smtp.Network.Host == null) ? false : true;
        }
    }
}
